﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyDBconnection;
using System.Security.Cryptography;
using System.Data.Odbc;
using Cat;

namespace Thesis_2
{
    public partial class frmPOS : Form
    {
        DatabaseConnection dbcon = new DatabaseConnection();
        CultureInfoConverter culture = new CultureInfoConverter();
        NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
        ConnectionString cs = new ConnectionString();
        OdbcCommand cmd = null;
        OdbcDataReader rdr = null;
        OdbcConnection con = null;


        public frmPOS()
        {
            InitializeComponent();
            dataGridView1.RowPostPaint += new DataGridViewRowPostPaintEventHandler(dataGridView1_RowPostPaint);
            txtProdSearch.TextChanged += new EventHandler(txtProdSearch_TextChanged);
            dataGridView1.RowHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataGridView1_RowHeaderMouseClick);
            txtQuantity.TextChanged += new EventHandler(txtQuantity_TextChanged);
            btnBrowse.Click += new EventHandler(btnBrowse_Click);
            btnAdd.Click += new EventHandler(btnAdd_Click);
            btnCashTend.Click += new EventHandler(btnCashTend_Click);
            txtQuantity.Validating += new CancelEventHandler(txtQuantity_Validating);
            txtCash.KeyPress += new KeyPressEventHandler(txtCash_KeyPress);
            btnProceed.Click += new EventHandler(btnProceed_Click);
            txtQuantity.KeyPress += new KeyPressEventHandler(txtQuantity_KeyPress);
            btnCloseCash.Click += new EventHandler(btnCloseCash_Click);
            this.Load += new EventHandler(frmPOS_Load);
            txtTotalPayment.TextChanged += new EventHandler(txtTotalPayment_TextChanged);
            btnsave.Click += new EventHandler(btnsave_Click);
            btnRemove.Click += new EventHandler(btnRemove_Click);
            ListView1.SelectedIndexChanged += new EventHandler(ListView1_SelectedIndexChanged);
        }

        void ListView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnRemove.Enabled = true;
        }
        void btnRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (ListView1.Items.Count == 0)
                {
                    MessageBox.Show("No items to remove", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    int itmCnt = 0;
                    int i = 0;
                    int t = 0;

                    ListView1.FocusedItem.Remove();
                    itmCnt = ListView1.Items.Count;
                    t = 1;

                    for (i = 1; i <= itmCnt + 1; i++)
                    {
                        //Dim lst1 As New ListViewItem(i)
                        //ListView1.Items(i).SubItems(0).Text = t
                        t = t + 1;

                    }
                    txtSubTotal.Text = subtot().ToString();
                    Calculate();
                }

                btnRemove.Enabled = false;
                if (ListView1.Items.Count == 0)
                {
                    txtSubTotal.Text = "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void txtQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        void txtTotalPayment_TextChanged(object sender, EventArgs e)
        {
            int val1 = 0;
            int val2 = 0;
            int.TryParse(txtTotal.Text, out val1);
            int.TryParse(txtTotalPayment.Text, out val2);
            int I = (val1 - val2);
            txtChange.Text = I.ToString();
        }
        void btnsave_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtTotalPayment.Text == "")
                {
                    MessageBox.Show("Please enter amount Tendered", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtTotalPayment.Focus();
                    return;
                }
                if (ListView1.Items.Count == 0)
                {
                    MessageBox.Show("sorry no product added", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string ct = "Select InvoiceNo from tblsales where InvoiceNo='" + txtInvoiceNo.Text + "'";
                cmd = new OdbcCommand(ct);
                cmd.Connection = con;
                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    MessageBox.Show("Invoice number Already used", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if ((rdr != null))
                    {
                        rdr.Close();
                    }
                    return;
                }

                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string cb = "Insert Into tblsales(InvoiceNo,CustomerName,SubTotal,VAT,VATAmount,GrandTotal,AmountTendered,ChangeDue) VALUES ('" + txtInvoiceNo.Text + "','" + txtCustomername.Text + "','" + txtSubTotal.Text + "','" + txtTaxPer.Text + "','" + txtTaxAmt.Text + "','" + txtTotal.Text + "','" + txtTotalPayment.Text + "','" + txtChange.Text + "')";
                cmd = new OdbcCommand(cb);
                cmd.Connection = con;
                cmd.ExecuteReader();
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Close();


                /*
                dbcon.dbconnection();
                dbcon.AddData("Insert into tblsales(InvoiceNo,CustomerName,Subtotal,VAT,VATAmount,GrandTotal,AmountTendered,Change)" + "VALUES ('" + txtInvoice.Text + "','" + txtCustomername.Text + "','" +txtSubTotal.Text  + "','" + txtTaxPer.Text + "','" + txtTaxAmt.Text + "','" + txtTotal.Text + "','" + txtTotalPayment.Text+"','" + txtChange.Text+ "')");
                dbcon.DBClose();
                 */

                /* for (int i = 0; i <= ListView1.Items.Count - 1; i++)
                 {
                     con = new OdbcConnection(cs.DBConn);

                     string cd = "Insert into tblproductsold(InvoiceNo,ProductID,Quantity,Price,TotalAmount) VALUES (@Invoiceno,@ProductID,@Quantity,@Price,@Totalamount)";
                     cmd = new OdbcCommand(cd);
                     cmd.Connection = con;
                     cmd.Parameters.AddWithValue("Invoiceno",txtInvoiceNo.Text);
                     cmd.Parameters.AddWithValue("ProductID",ListView1.Items[i].SubItems[1].Text);
                     cmd.Parameters.AddWithValue("Quantity",ListView1.Items[i].SubItems[4].Text);
                     cmd.Parameters.AddWithValue("Price", ListView1.Items[i].SubItems[3].Text);
                     cmd.Parameters.AddWithValue("TotalAmount", ListView1.Items[i].SubItems[5].Text);
                     con.Open();
                     cmd.ExecuteNonQuery();
                     con.Close();
                 }
                 */

                for (int i = 0; i <= ListView1.Items.Count - 1; i++)
                {
                    con = new OdbcConnection(cs.DBConn);
                    con.Open();
                    string cb1 = "Update tblstock set Quantity = Quantity - " + ListView1.Items[i].SubItems[4].Text + " where ProductID = " + ListView1.Items[i].SubItems[1].Text + "";
                    cmd = new OdbcCommand(cb1);
                    cmd.Connection = con;
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                getproduct();
                ListView1.Items.Clear();
                AutoInv();
                txtSubTotal.Text = "";
                txtTaxAmt.Text = "";
                txtTotalAmount.Text = "";
                txtTotalPayment.Text = "";
                txtTotal.Text = "";
                txtChange.Text = "";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }
        void btnCloseCash_Click(object sender, EventArgs e)
        {
            panel1.Hide();
        }
        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[62];
            chars = "123456789".ToCharArray();
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }
        public void AutoInv()
        {
            txtInvoiceNo.Text = "Inv-" + GetUniqueKey(6);
        }
        void btnProceed_Click(object sender, EventArgs e)
        {
            if (txtCash.Text == "")
            {
                MessageBox.Show("Please Enter Amount", "No input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCash.Focus();
                return;
            }
            int val1 = 0;
            int val2 = 0;
            int.TryParse(txtTotal.Text, out val1);
            int.TryParse(txtCash.Text, out val2);
            if (val2 >= val1)
            {
                txtTotalPayment.Text = txtCash.Text;
                int I = (val2 - val1);
                txtChange.Text = I.ToString();
                txtCash.Text = "";
                panel1.Visible = false;

            }
            else
            {
                MessageBox.Show("Kurang ti payment yo ah", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCash.Text = "";
                txtCash.Focus();

                return;
            }
        }
        void txtCash_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
            {
                e.Handled = true;
                return;
            }
        }
        void btnCashTend_Click(object sender, EventArgs e)
        {
            panel1.BringToFront();
            panel1.Visible = true;
            panel1.SetBounds(330, 118, 472, 291);
            txtCash.Focus();
        }
        void txtQuantity_Validating(object sender, CancelEventArgs e)
        {
            int val1 = 0;
            int val2 = 0;
            int.TryParse(txtStocks.Text, out val1);
            int.TryParse(txtQuantity.Text, out val2);
            if (val2 > val1)
            {
                MessageBox.Show("Selling quantities are more than available quantities", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtQuantity.Text = "";
                txtTotalAmount.Text = "";
                txtQuantity.Focus();
                return;
            }
        }
        public double subtot()
        {
            int i = 0;
            int j = 0;
            int k = 0;
            i = 0;
            j = 0;
            k = 0;
            try
            {
                j = ListView1.Items.Count;
                for (i = 0; i <= j - 1; i++)
                {
                    k = k + Convert.ToInt32(ListView1.Items[i].SubItems[5].Text);
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return k;
        }
        void txtQuantity_TextChanged(object sender, EventArgs e)
        {
            int val1 = 0;
            int val2 = 0;
            int.TryParse(txtPrice.Text, out val1);
            int.TryParse(txtQuantity.Text, out val2);
            int I = (val1 * val2);
            txtTotalAmount.Text = I.ToString();
        }
        void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtCustomername.Text == "")
                {
                    MessageBox.Show("Please retrieve Customer ID", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtCustomername.Focus();
                    return;
                }

                if (txtProdname.Text == "")
                {
                    MessageBox.Show("Please retrieve product name", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (txtQuantity.Text == "")
                {
                    MessageBox.Show("Please enter no. of sale quantity", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtQuantity.Focus();
                    return;
                }
                int SaleQty = Convert.ToInt32(txtQuantity.Text);
                if (SaleQty == 0)
                {
                    MessageBox.Show("no. of sale quantity can not be zero", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtQuantity.Focus();
                    return;
                }

                if (ListView1.Items.Count == 0)
                {
                    ListViewItem lst = new ListViewItem();
                    lst.SubItems.Add(txtProdID.Text);
                    lst.SubItems.Add(txtProdname.Text);
                    lst.SubItems.Add(txtPrice.Text);
                    lst.SubItems.Add(txtQuantity.Text);
                    lst.SubItems.Add(txtTotalAmount.Text);
                    ListView1.Items.Add(lst);
                    txtSubTotal.Text = subtot().ToString();

                    if (txtTaxPer.Text != "")
                    {
                        txtTaxAmt.Text = Convert.ToInt32((Convert.ToInt32(txtSubTotal.Text) * Convert.ToDouble(txtTaxPer.Text) / 100)).ToString();
                        txtTotal.Text = (Convert.ToInt32(txtSubTotal.Text) + Convert.ToInt32(txtTaxAmt.Text)).ToString();
                    }
                    int val1 = 0;
                    int val2 = 0;
                    int.TryParse(txtTotal.Text, out val1);
                    int.TryParse(txtTotalPayment.Text, out val2);
                    int I = (val1 - val2);
                    // txtPaymentDue.Text = I.ToString();
                    txtProdname.Text = "";
                    txtPrice.Text = "";
                    txtQuantity.Text = "";
                    txtStocks.Text = "";
                    txtTotalAmount.Text = "";
                    txtProdSearch.Text = "";
                    txtProdID.Text = "";
                    return;
                }

                for (int j = 0; j <= ListView1.Items.Count - 1; j++)
                {
                    if (ListView1.Items[j].SubItems[1].Text == txtProdID.Text)
                    {
                        ListView1.Items[j].SubItems[1].Text = txtProdID.Text;
                        ListView1.Items[j].SubItems[2].Text = txtProdname.Text;
                        ListView1.Items[j].SubItems[3].Text = txtPrice.Text;
                        ListView1.Items[j].SubItems[4].Text = (Convert.ToInt32(ListView1.Items[j].SubItems[4].Text) + Convert.ToInt32(txtQuantity.Text)).ToString();
                        ListView1.Items[j].SubItems[5].Text = (Convert.ToInt32(ListView1.Items[j].SubItems[5].Text) + Convert.ToInt32(txtTotalAmount.Text)).ToString();
                        txtSubTotal.Text = subtot().ToString();
                        if (txtTaxPer.Text != "")
                        {
                            txtTaxAmt.Text = Convert.ToInt32((Convert.ToInt32(txtSubTotal.Text) * Convert.ToDouble(txtTaxPer.Text) / 100)).ToString();
                            txtTotal.Text = (Convert.ToInt32(txtSubTotal.Text) + Convert.ToInt32(txtTaxAmt.Text)).ToString();
                        }
                        int val1 = 0;
                        int val2 = 0;
                        int.TryParse(txtTotal.Text, out val1);
                        int.TryParse(txtTotalPayment.Text, out val2);
                        int I = (val1 - val2);
                        //  txtPaymentDue.Text = I.ToString();
                        txtProdID.Text = "";
                        txtProdname.Text = "";
                        txtPrice.Text = "";
                        txtStocks.Text = "";
                        txtQuantity.Text = "";
                        txtTotalAmount.Text = "";
                        return;

                    }
                }

                ListViewItem lst1 = new ListViewItem();

                lst1.SubItems.Add(txtProdID.Text);
                lst1.SubItems.Add(txtProdname.Text);
                lst1.SubItems.Add(txtPrice.Text);
                lst1.SubItems.Add(txtQuantity.Text);
                lst1.SubItems.Add(txtTotalAmount.Text);
                ListView1.Items.Add(lst1);
                txtSubTotal.Text = subtot().ToString();
                if (txtTaxPer.Text != "")
                {
                    txtTaxAmt.Text = Convert.ToInt32((Convert.ToInt32(txtSubTotal.Text) * Convert.ToDouble(txtTaxPer.Text) / 100)).ToString();
                    txtTotal.Text = (Convert.ToInt32(txtSubTotal.Text) + Convert.ToInt32(txtTaxAmt.Text)).ToString();
                }
                /*
                 int val3 = 0;
                 int val4 = 0;
                 int.TryParse(txtTotal.Text, out val3);
                 int.TryParse(txtTotalPayment.Text, out val4);
                 int I1 = (val3 - val4);
                 txtPaymentDue.Text = I1.ToString();
                 */
                txtProdname.Text = "";
                txtProdID.Text = "";
                txtPrice.Text = "";
                txtStocks.Text = "";
                txtQuantity.Text = "";
                txtTotalAmount.Text = "";
                return;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        void btnBrowse_Click(object sender, EventArgs e)
        {
            frmCustomerList frmC = new frmCustomerList();
            frmC.Show();
            this.Hide();
        }
        void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewRow dr = dataGridView1.SelectedRows[0];
            txtProdID.Text = dr.Cells[0].Value.ToString();
            txtProdname.Text = dr.Cells[1].Value.ToString();
            txtPrice.Text = dr.Cells[2].Value.ToString();
            txtStocks.Text = dr.Cells[3].Value.ToString();
        }
        void txtProdSearch_TextChanged(object sender, EventArgs e)
        {
            if (txtProdSearch.Text != "Search Product")
            {
                dbcon.dbconnection();
                // dbcon.loadData("SELECT  * FROM tblprice WHERE ProductName or ProductID LIKE '%" + txtsearch.Text + "%'");
                dbcon.loadData("Select tblprice.ProductID,tblproduct.ProductName,tblprice.SuggestedPrice,tblstock.Quantity from tblprice INNER JOIN tblproduct ON tblprice.ProductID=tblproduct.ProductID INNER JOIN tblstock ON tblprice.ProductID=tblstock.ProductID WHERE tblprice.ProductID LIKE '%" + txtProdSearch.Text + "%'");
                dataGridView1.DataSource = dbcon.tbl;
                dbcon.DBClose();
            }
            else
            {
                getproduct();
            }
        }
        void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            string strRowNumber = (e.RowIndex + 1).ToString();
            SizeF size = e.Graphics.MeasureString(strRowNumber, this.Font);
            if (dataGridView1.RowHeadersWidth < Convert.ToInt32((size.Width + 10)))
            {
                dataGridView1.RowHeadersWidth = Convert.ToInt32((size.Width + 10));
            }
            Brush b = SystemBrushes.ControlText;
            e.Graphics.DrawString(strRowNumber, this.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2));
        }
        private void frmPOS_Load(object sender, EventArgs e)
        {
            getproduct();
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            AutoInv();
            txtCustomername.Text = "Walk in";


        }
        void getproduct()
        {
            dbcon.dbconnection();
            dbcon.loadData("Select tblprice.ProductID,tblproduct.ProductName,tblprice.SuggestedPrice,tblstock.Quantity from tblprice INNER JOIN tblproduct ON tblprice.ProductID=tblproduct.ProductID INNER JOIN tblstock ON tblprice.ProductID=tblstock.ProductID ");
            dataGridView1.DataSource = dbcon.tbl;
            dbcon.DBClose();
            dataGridView1.Columns[2].DefaultCellStyle.Format = "#,#0.00";
            dataGridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridView1.Columns[3].DefaultCellStyle.Format = "#,#0.00";
            dataGridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            Refresh();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (txtTotal.Text != "")
            {
                DialogResult result;
                result = MessageBox.Show("You have current Transaction, Are your sure to Continue?", "Cancel Transaction", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    ListView1.Items.Clear();
                    AutoInv();
                    txtSubTotal.Text = "";
                    txtTaxAmt.Text = "";
                    txtTotalAmount.Text = "";
                    txtTotalPayment.Text = "";
                    txtTotal.Text = "";
                    txtChange.Text = "";

                }
                else
                {
                    this.Show();
                    txtProdname.Text = "";
                    txtPrice.Text = "";
                    txtQuantity.Text = "";
                    txtStocks.Text = "";
                    txtTotalAmount.Text = "";
                    txtProdSearch.Text = "";
                    txtProdID.Text = "";
                }
            }


        }
        public void Calculate()
        {
            if (txtTaxPer.Text != "")
            {
                txtTaxAmt.Text = Convert.ToInt32((Convert.ToInt32(txtSubTotal.Text) * Convert.ToDouble(txtTaxPer.Text) / 100)).ToString();

            }
            
            int val1 = 0;
            int val2 = 0;
            int val3 = 0;
            int val4 = 0;
            int val5 = 0;
            int.TryParse(txtTaxAmt.Text, out val1);
            int.TryParse(txtSubTotal.Text, out val2);
            //int.TryParse(txtDiscountAmount.Text, out val3);
            int.TryParse(txtTotal.Text, out val4);
            int.TryParse(txtTotalPayment.Text, out val5);
            val4 = val1 + val2 - val3;
            txtTotal.Text = val4.ToString();
            int I = (val4 - val5);
            //txtPayment.Text = I.ToString();


        }
    }
}
